package com.ybdz.scanner.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ybdz.scanner.R;
import com.ybdz.scanner.api.ApiStore;
import com.ybdz.scanner.base.BaseActivity;
import com.ybdz.scanner.bean.UpdataBean;
import com.ybdz.scanner.utils.Commen;
import com.ybdz.scanner.utils.MyApplication;
import com.ybdz.scanner.utils.MyToast;
import com.ybdz.scanner.utils.SPUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 主界面
 */
public class MainActivity extends BaseActivity {

    @BindView(R.id.account)
    ImageView mAccount;
    @BindView(R.id.rl_deposit)
    RelativeLayout mRlDeposit;
    @BindView(R.id.rl_take)
    RelativeLayout mRlTake;
    @BindView(R.id.rl_query)
    RelativeLayout mRlQuery;


    public static boolean isExit = false;

    private BroadcastReceiver broadcastReceiver;
    private int REQUESTPERMISSION;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        String name = SPUtils.getString(MainActivity.this, "usename", "deUseName");
        isLogining(name);

        updatas();   //手持端固定3

    }

    private void updatas() {
        ApiStore.update().enqueue(new Callback<UpdataBean>() {

            private AlertDialog updateDialog;

            @Override
            public void onResponse(Call<UpdataBean> call, Response<UpdataBean> response) {
                UpdataBean body = response.body();
                if(body != null){
                    String code = body.getCode();
                    if(code.equals("00")){   //访问成功
                        String onlineVersion = body.getVersion();
                        final String appUrl = body.getAppUrl();
                        //判断是否强制更新；
                        final String isForce = body.getIsForce();

                        String regex = "^[0-9]*$";
                        String regex2 = "^[1-9]*$";
                        String s = String.valueOf(onlineVersion.charAt(0));

                        //获取本地版本号
                        String packageName = MainActivity.this.getPackageName();
                        try {
                            PackageInfo packageInfo1 = MainActivity.this.getPackageManager().getPackageInfo(packageName, 0);
                            int loacalVersionCode = packageInfo1.versionCode;

                            if (s.matches(regex2)){                        //判断非0开头；
                                if (onlineVersion.matches(regex)){        //判断version是全数字字符；
                                    //版本号对比，确定更新；
                                    if (Integer.parseInt(onlineVersion) > loacalVersionCode){
                                        //app更新地址为空，不弹出更新框；
                                        if (appUrl == null || appUrl.length() == 0){
                                            return;
                                        }

                                        //清空下载文件夹
                                        Commen.delFolder();

                                        //弹出更新对话框
                                        MainActivity.this.runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {

                                                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.UpdateDialog);
                                                updateDialog = builder.create();
                                                if (!MainActivity.this.isFinishing()){
                                                    updateDialog.show();
                                                    updateDialog.setCancelable(false);
                                                    Window window = updateDialog.getWindow();
                                                    if (window != null){
                                                        window.setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
                                                        if (!isForce.equals("true")){
                                                            window.setContentView(R.layout.activity_update_dialog_choice);
                                                            TextView updata_ignor = (TextView) window.findViewById(R.id.updata_ignor);
                                                            TextView updata_now = (TextView) window.findViewById(R.id.updata_now);

                                                            updata_ignor.setOnClickListener(new View.OnClickListener() {
                                                                @Override
                                                                public void onClick(View v) {
                                                                    updateDialog.dismiss();
                                                                }
                                                            });

                                                            updata_now.setOnClickListener(new View.OnClickListener() {
                                                                @Override
                                                                public void onClick(View v) {
                                                                    DownLoad(appUrl);
                                                                    updateDialog.dismiss();
                                                                }
                                                            });

                                                        }else {
                                                            window.setContentView(R.layout.activity_update_dialog);
                                                            TextView update = (TextView) window.findViewById(R.id.tv_updata);
                                                            update.setOnClickListener(new View.OnClickListener() {
                                                                @Override
                                                                public void onClick(View v) {
                                                                    DownLoad(appUrl);
                                                                    updateDialog.dismiss();
                                                                }
                                                            });
                                                        }

                                                    }
                                                }


                                            }
                                        });
                                    }
                                }
                            }
                        } catch (PackageManager.NameNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<UpdataBean> call, Throwable t) {

            }
        });
    }

    private void DownLoad(String appUrl) {
        DownloadManager manager = (DownloadManager)MainActivity.this.getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(appUrl));
        // 设置允许的连接来处理下载
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
                | DownloadManager.Request.NETWORK_WIFI);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalPublicDir(Commen.SAVE_APP_LOCATION, Commen.SAVE_APP_NAME);
        // 不设置漫游下载
        request.setAllowedOverRoaming(false);
        request.allowScanningByMediaScanner();
        request.setVisibleInDownloadsUi(true);
        request.setTitle("手持端更新数据中..");

        if (manager != null){
            long loadid = manager.enqueue(request);

            DownloadManager.Query query = new DownloadManager.Query();
            DownloadManager.Query filterById = query.setFilterById(loadid);
            Cursor c = manager.query(filterById);
            if (c != null && c.moveToFirst()){

                listener(loadid);
            }
        }
    }

    private void listener(final long loadid) {
        // 注册广播监听系统的下载完成事件。
        IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);

        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                long ID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (ID == loadid) {
                    //自动安装apk代码；
                    String filePath = Commen.APP_FILE_NAME;
                    Intent install = new Intent();
                    install.setAction(android.content.Intent.ACTION_VIEW);
                    install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    install.addCategory("android.intent.category.DEFAULT");
                    install.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
                    MainActivity.this.startActivity(install);
                }
            }
        };

        registerReceiver(broadcastReceiver, intentFilter);
    }

    /**
     * 判定登录状态
     *
     * @param name
     */
    private void isLogining(String name) {
        if (name.equals("deUseName")) {
            SPUtils.saveString(MainActivity.this, "usename", null);
//            SPUtils.saveBoolean(MainActivity.this,"ISLOGIN",false);
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
        }
    }


    @OnClick({R.id.account, R.id.rl_deposit, R.id.rl_take, R.id.rl_query})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.account:              //账户入口
                startActivity(new Intent(MainActivity.this, AccountActivity.class));
                break;
            case R.id.rl_deposit:           //入库
                startActivity(new Intent(MainActivity.this, LuKuActivity.class));
                break;
            case R.id.rl_take:              //出库
                startActivity(new Intent(MainActivity.this, ChuKuActivity.class));
                break;
            case R.id.rl_query:              //查询
                startActivity(new Intent(MainActivity.this, QueryScanActivity.class));
                break;
        }

//        boolean islogin = SPUtils.getBoolean(MainActivity.this, "ISLOGIN", false);
//        if (islogin){
//
//        }else {
//            startActivity(new Intent(MainActivity.this,LoginActivity.class));
//        }

    }

    /**
     * 连按两次退出app
     *
     * @param keyCode
     * @param event
     * @return
     */
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            exit();
//            return false;
//        }
//        return super.onKeyDown(keyCode, event);
//    }


//    private void exit() {
//        if (!isExit) {
//            isExit = true;
//            MyToast.show(MainActivity.this, "再按一次退出程序");
//            // 利用handler延迟发送更改状态信息
//            mHandler.sendEmptyMessageDelayed(0, 2000);
//        } else {
//
//            finish();
//            System.exit(0);
//        }
//    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (broadcastReceiver != null){
            unregisterReceiver(broadcastReceiver);

        }
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();   //去掉退出按钮
    }
}
